using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using System.Text;
using System.Text.Json;
using MVCWeekOne.Models;

namespace MVCWeekOne.Controllers
{
    public class PermissionController : Controller
    {
        private readonly IHttpClientFactory _httpClientFactory;
        private readonly ApiSettings _apiSettings;

        public PermissionController(IHttpClientFactory httpClientFactory, IOptions<ApiSettings> apiSettings)
        {
            _httpClientFactory = httpClientFactory;
            _apiSettings = apiSettings.Value;
        }

        [HttpGet]
        public async Task<IActionResult> PermissionManagement()
        {
            var token = HttpContext.Session.GetString("Token");
            if (string.IsNullOrEmpty(token))
            {
                return RedirectToAction("Login", "Account");
            }

            try
            {
                var client = _httpClientFactory.CreateClient();
                client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");

                var response = await client.GetAsync($"{_apiSettings.ReadApiUrl}/Permission/GetAllPermission");
                
                if (response.IsSuccessStatusCode)
                {
                    var result = await response.Content.ReadAsStringAsync();
                    var permissionResult = JsonSerializer.Deserialize<ApiResult<List<PermissionModel>>>(result);
                    
                    if (permissionResult?.IsSuccess == true)
                    {
                        return View(permissionResult.Data);
                    }
                }

                return View(new List<PermissionModel>());
            }
            catch
            {
                return View(new List<PermissionModel>());
            }
        }

        /// <summary>
        /// 获取权限分页数据
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetPermissionPage(int page = 1, int limit = 10, string permissionName = "")
        {
            var token = HttpContext.Session.GetString("Token");
            if (string.IsNullOrEmpty(token))
            {
                return Json(new { code = 1, msg = "未登录", count = 0, data = new List<PermissionModel>() });
            }

            try
            {
                var client = _httpClientFactory.CreateClient();
                client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");

                // 构建查询参数 - 只保留权限名称查询
                var queryParams = new List<string>();
                if (!string.IsNullOrEmpty(permissionName))
                    queryParams.Add($"PermissionName={Uri.EscapeDataString(permissionName)}");
                
                queryParams.Add($"Index={page}");
                queryParams.Add($"Size={limit}");
                
                var queryString = string.Join("&", queryParams);
                var url = $"{_apiSettings.ReadApiUrl}/Permission/GetPermission?{queryString}";

                System.Diagnostics.Debug.WriteLine($"调用权限API: {url}");

                var response = await client.GetAsync(url);
                
                if (response.IsSuccessStatusCode)
                {
                    var result = await response.Content.ReadAsStringAsync();
                    System.Diagnostics.Debug.WriteLine($"权限API返回: {result}");
                    
                    var permissionResult = JsonSerializer.Deserialize<ApiPageing<PermissionModel>>(result);
                    
                    if (permissionResult != null)
                    {
                        return Json(new { 
                            code = 0, 
                            msg = "success", 
                            count = permissionResult.TotaCount,
                            data = permissionResult.PageData ?? new List<PermissionModel>()
                        });
                    }
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine($"权限API调用失败: {response.StatusCode}");
                }

                return Json(new { code = 1, msg = "获取权限数据失败", count = 0, data = new List<PermissionModel>() });
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"权限API异常: {ex.Message}");
                return Json(new { code = 1, msg = $"获取权限数据异常: {ex.Message}", count = 0, data = new List<PermissionModel>() });
            }
        }

        /// <summary>
        /// 根据ID获取权限详情
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetPermissionById(long id)
        {
            var token = HttpContext.Session.GetString("Token");
            if (string.IsNullOrEmpty(token))
            {
                return Json(new { success = false, message = "未登录" });
            }

            try
            {
                var client = _httpClientFactory.CreateClient();
                client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");

                var response = await client.GetAsync($"{_apiSettings.ReadApiUrl}/Permission/GetPermissionById?id={id}");
                
                if (response.IsSuccessStatusCode)
                {
                    var result = await response.Content.ReadAsStringAsync();
                    var permissionResult = JsonSerializer.Deserialize<ApiResult<PermissionModel>>(result);
                    
                    if (permissionResult?.IsSuccess == true)
                    {
                        return Json(new { success = true, data = permissionResult.Data });
                    }
                }

                return Json(new { success = false, message = "获取权限数据失败" });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = $"获取权限数据异常: {ex.Message}" });
            }
        }

        /// <summary>
        /// 获取权限树形结构数据
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetPermissionTree()
        {
            var token = HttpContext.Session.GetString("Token");
            if (string.IsNullOrEmpty(token))
            {
                return Json(new { success = false, message = "未登录" });
            }

            try
            {
                var client = _httpClientFactory.CreateClient();
                client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");

                var response = await client.GetAsync($"{_apiSettings.ReadApiUrl}/Permission/GetAllPermission");
                
                if (response.IsSuccessStatusCode)
                {
                    var result = await response.Content.ReadAsStringAsync();
                    var permissionResult = JsonSerializer.Deserialize<ApiResult<List<PermissionModel>>>(result);
                    
                    if (permissionResult?.IsSuccess == true && permissionResult.Data != null)
                    {
                        var treeData = BuildPermissionTree(permissionResult.Data);
                        return Json(new { success = true, data = treeData });
                    }
                }

                return Json(new { success = false, message = "获取权限数据失败" });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = $"获取权限数据异常: {ex.Message}" });
            }
        }

        /// <summary>
        /// 构建权限树形结构
        /// </summary>
        private List<PermissionTreeNode> BuildPermissionTree(List<PermissionModel> permissions)
        {
            var treeData = new List<PermissionTreeNode>();
            var permissionMap = new Dictionary<long, PermissionTreeNode>();

            // 创建所有节点的映射
            foreach (var permission in permissions)
            {
                permissionMap[permission.Id] = new PermissionTreeNode
                {
                    Id = permission.Id,
                    Title = permission.PermissionName,
                    PermissionName = permission.PermissionName,
                    PermissionURL = permission.PermissionURL,
                    ParentId = permission.ParentId,
                    IsState = permission.IsState,
                    CreateTime = permission.CreateTime,
                    Children = new List<PermissionTreeNode>()
                };
            }

            // 构建树形结构
            foreach (var permission in permissions)
            {
                var node = permissionMap[permission.Id];
                if (permission.ParentId == 0)
                {
                    // 顶级节点
                    treeData.Add(node);
                }
                else
                {
                    // 子节点
                    var parentIdLong = (long)permission.ParentId;
                    if (permissionMap.ContainsKey(parentIdLong))
                    {
                        permissionMap[parentIdLong].Children.Add(node);
                    }
                }
            }

            return treeData;
        }

        [HttpPost]
        public async Task<IActionResult> AddPermission([FromBody] AddPermissionViewModel model)
        {
            var token = HttpContext.Session.GetString("Token");
            if (string.IsNullOrEmpty(token))
            {
                return Json(new { success = false, message = "未登录" });
            }

            try
            {
                System.Diagnostics.Debug.WriteLine($"添加权限请求: PermissionName={model.PermissionName}, PermissionURL={model.PermissionURL}, ParentId={model.ParentId}");

                var client = _httpClientFactory.CreateClient();
                client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");

                var permissionData = new
                {
                    PermissionName = model.PermissionName,
                    PermissionURL = model.PermissionURL,
                    ParentId = model.ParentId
                };

                var json = JsonSerializer.Serialize(permissionData);
                var content = new StringContent(json, Encoding.UTF8, "application/json");

                System.Diagnostics.Debug.WriteLine($"发送到后端API的数据: {json}");

                // 根据API定义，添加权限是POST /api/Permission/AddPermission
                var response = await client.PostAsync($"{_apiSettings.WriteApiUrl}/Permission/AddPermission", content);
                
                if (response.IsSuccessStatusCode)
                {
                    var result = await response.Content.ReadAsStringAsync();
                    System.Diagnostics.Debug.WriteLine($"后端API响应: {result}");
                    
                    var addResult = JsonSerializer.Deserialize<ApiResult<int>>(result);
                    
                    if (addResult?.IsSuccess == true)
                    {
                        return Json(new { success = true, message = "添加成功" });
                    }
                    else
                    {
                        return Json(new { success = false, message = addResult?.Msg ?? "添加失败" });
                    }
                }
                else
                {
                    var errorContent = await response.Content.ReadAsStringAsync();
                    System.Diagnostics.Debug.WriteLine($"后端API错误响应: {response.StatusCode} - {errorContent}");
                    return Json(new { success = false, message = $"添加失败: {response.StatusCode}" });
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"添加权限异常: {ex.Message}");
                return Json(new { success = false, message = $"添加失败: {ex.Message}" });
            }
        }

        [HttpPost]
        public async Task<IActionResult> UpdatePermission([FromBody] UpdatePermissionViewModel model)
        {
            var token = HttpContext.Session.GetString("Token");
            if (string.IsNullOrEmpty(token))
            {
                return Json(new { success = false, message = "未登录" });
            }

            try
            {
                System.Diagnostics.Debug.WriteLine($"更新权限请求: Id={model.Id}, PermissionName={model.PermissionName}, PermissionURL={model.PermissionURL}, ParentId={model.ParentId}");

                var client = _httpClientFactory.CreateClient();
                client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");

                var permissionData = new
                {
                    Id = model.Id,
                    PermissionName = model.PermissionName,
                    PermissionURL = model.PermissionURL,
                    ParentId = model.ParentId
                };

                var json = JsonSerializer.Serialize(permissionData);
                var content = new StringContent(json, Encoding.UTF8, "application/json");

                System.Diagnostics.Debug.WriteLine($"发送到后端API的数据: {json}");

                // 根据API定义，更新权限是PUT /api/Permission/UpdatePermission
                var response = await client.PutAsync($"{_apiSettings.WriteApiUrl}/Permission/UpdatePermission", content);
                
                if (response.IsSuccessStatusCode)
                {
                    var result = await response.Content.ReadAsStringAsync();
                    System.Diagnostics.Debug.WriteLine($"后端API响应: {result}");
                    
                    var updateResult = JsonSerializer.Deserialize<ApiResult<int>>(result);
                    
                    if (updateResult?.IsSuccess == true)
                    {
                        return Json(new { success = true, message = "更新成功" });
                    }
                    else
                    {
                        return Json(new { success = false, message = updateResult?.Msg ?? "更新失败" });
                    }
                }
                else
                {
                    var errorContent = await response.Content.ReadAsStringAsync();
                    System.Diagnostics.Debug.WriteLine($"后端API错误响应: {response.StatusCode} - {errorContent}");
                    return Json(new { success = false, message = $"更新失败: {response.StatusCode}" });
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"更新权限异常: {ex.Message}");
                return Json(new { success = false, message = $"更新失败: {ex.Message}" });
            }
        }

        [HttpPost]
        public async Task<IActionResult> DeletePermission([FromBody] DeletePermissionViewModel model)
        {
            var token = HttpContext.Session.GetString("Token");
            if (string.IsNullOrEmpty(token))
            {
                return Json(new { success = false, message = "未登录" });
            }

            try
            {
                System.Diagnostics.Debug.WriteLine($"删除权限请求: Id={model.PermissionId}");

                var client = _httpClientFactory.CreateClient();
                client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");

                // 根据API定义，删除权限是DELETE /api/Permission/DeletePermission，参数通过Query String传递
                var response = await client.DeleteAsync($"{_apiSettings.WriteApiUrl}/Permission/DeletePermission?Id={model.PermissionId}");
                
                if (response.IsSuccessStatusCode)
                {
                    var result = await response.Content.ReadAsStringAsync();
                    System.Diagnostics.Debug.WriteLine($"删除权限API响应: {result}");
                    
                    var deleteResult = JsonSerializer.Deserialize<ApiResult<int>>(result);
                    
                    if (deleteResult?.IsSuccess == true)
                    {
                        return Json(new { success = true, message = "删除成功" });
                    }
                    else
                    {
                        return Json(new { success = false, message = deleteResult?.Msg ?? "删除失败" });
                    }
                }
                else
                {
                    var errorContent = await response.Content.ReadAsStringAsync();
                    System.Diagnostics.Debug.WriteLine($"删除权限API错误响应: {response.StatusCode} - {errorContent}");
                    return Json(new { success = false, message = $"删除失败: {response.StatusCode}" });
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"删除权限异常: {ex.Message}");
                return Json(new { success = false, message = $"删除失败: {ex.Message}" });
            }
        }
    }

    /// <summary>
    /// 权限树形节点模型
    /// </summary>
    public class PermissionTreeNode
    {
        public long Id { get; set; }
        public string Title { get; set; } = string.Empty;
        public string PermissionName { get; set; } = string.Empty;
        public string PermissionURL { get; set; } = string.Empty;
        public int ParentId { get; set; }
        public bool IsState { get; set; }
        public DateTime CreateTime { get; set; }
        public List<PermissionTreeNode> Children { get; set; } = new List<PermissionTreeNode>();
    }
}
